package cn.chowx.myjfinal.shiro;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import cn.chowx.myjfinal.system.model.SysAction;
import cn.chowx.myjfinal.system.model.SysRole;
import cn.dreampie.shiro.core.JdbcAuthzService;
import cn.dreampie.shiro.core.handler.AuthzHandler;
import cn.dreampie.shiro.core.handler.JdbcPermissionAuthzHandler;


public class MyJdbcAuthzService implements JdbcAuthzService {

	@Override
	public Map<String, AuthzHandler> getJdbcAuthz() {
		//加载数据库的url配置
		//按长度倒序排列url
		Map<String, AuthzHandler> authzJdbcMaps = Collections.synchronizedMap(new TreeMap<String,AuthzHandler>(
			new Comparator<String>() {
				public int compare(String k1, String k2){
					int result = k2.length() - k1.length();
					if(result == 0){
						return k1.compareTo(k2);
					}
					return result;
				}
		}));
	
		//遍历角色
		List<SysRole> roles = SysRole.DAO.findList(1);
		List<SysAction> actions = new ArrayList<>();
		for(SysRole role : roles){
			actions = role.getActionsByRoleId();
			if(actions != null && !actions.isEmpty()){
				for(SysAction action : actions){
					if(action.getStr("url") != null && action.getStr("url").trim().length() > 0){
						authzJdbcMaps.put(action.getStr("url"),new JdbcPermissionAuthzHandler(action.getStr("value")));
					}
				}
			}
		}
		return authzJdbcMaps;
	}

}
